package com.cps116.friendstracker;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.cps116.parcelables.Coordinate;
import com.cps116.parcelables.LocationTraceList;
import com.cps116.parcelables.MapParcelableData;
import com.cps116.resource.HttpResponseDecoder;
import com.easy.facebook.android.apicall.FQL;
import com.easy.facebook.android.error.EasyFacebookError;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class QueryActivity_PlotPathOfFriendActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.queryactivity_plotpathoffriendactivity_layout);

		FQL facebookFQL = ((FriendsTrackerApplication) getApplication()).getFacebookFQL();
		ArrayList<String> friends = (ArrayList<String>)((FriendsTrackerApplication) getApplication()).getUser().getFriends();
		String[] friendsArray = ((FriendsTrackerApplication) getApplication()).getUser().getFriendsArray();

		ListView list=(ListView)findViewById(R.id.queryactivity_plotpathoffriend_query_listview);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, friendsArray);
		list.setAdapter(adapter);	

		list.setOnItemClickListener(new ListOptionSelector(this, facebookFQL, friends));

	}

	private class ListOptionSelector implements OnItemClickListener
	{
		Context context;
		FQL facebookFQL;
		ArrayList<String> friends;

		ListOptionSelector(Context c, FQL f, ArrayList<String> fr)
		{
			context = c;
			facebookFQL = f;
			friends = fr;
		}

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			//display this particular friend's check-ins
			Pattern p = Pattern.compile("(.+?),(.+)");
			Matcher m = p.matcher(friends.get(position));

			if(m.find())
			{
				//Get coordinates of a given user given their facebook uid

				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://dbcourse.cs.duke.edu/tnd6/FFQueries/pulllocationinfo.php");

				try
				{
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
					nameValuePairs.add(new BasicNameValuePair("userid", m.group(2)));

					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));					
					HttpResponse response = httpclient.execute(httppost);
					String locationsString = HttpResponseDecoder.getResponseBody(response);

					//if the user has no location information in the database, we'll catch those and display another screen that just says "No Location Information in Database"
					if(locationsString.equals(";"))
					{
						Log.d("No Location Information", "No Location Information in Database");
						startActivity(new Intent(context, QueryActivity_PlotPathOfFriendActivity_NoLocations.class));
					}
					else 
					{
						
					Log.d("TELL ME WHAT YOU GET", locationsString);

					Intent mapIntent = new Intent(context, FriendsFinderMapActivity.class);
					List<MapParcelableData> mapData = new ArrayList<MapParcelableData>();
					List<Coordinate> coords = new ArrayList<Coordinate>();

					Pattern coordsPattern = Pattern.compile("(.+?);(.+?);(.+?);(.+?);");
					Matcher coordsMatcher = coordsPattern.matcher(locationsString);

					while(coordsMatcher.find())
					{
						Log.d("COORDS", coordsMatcher.group(1) + "   " + coordsMatcher.group(2) + "   " + coordsMatcher.group(3) + "   " + coordsMatcher.group(4));

						//systematically adds the coordinates to the list
						coords.add(new Coordinate(Double.parseDouble(coordsMatcher.group(4)), Double.parseDouble(coordsMatcher.group(3))));
					}

					long updateTime = 10000;
					boolean toUpdate = true;

					MapParcelableData inputData = new MapParcelableData(coords, toUpdate, m.group(1), m.group(2), updateTime);
					mapData.add(inputData);

					LocationTraceList parcelableList = new LocationTraceList(mapData);
					mapIntent.putExtra("overlays", parcelableList);
					mapIntent.putExtra("update_time", updateTime);
					mapIntent.putExtra("need_to_update", toUpdate);

					startActivity(mapIntent);
					
					}
				}
				catch(Exception e)
				{
					Log.d("EXCEPTION", "EXCEPTION");
					e.printStackTrace();
				}

			}

		}
	}



	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
}
